// Mock数据，用于模拟后端API响应

// 模拟课程任务项数据
const mockSubitems = [
  // Vue 3 实战开发课程的任务项
  {
    id: 1,
    courseId: 1,
    title: 'Vue 3 基础入门',
    description: '学习Vue 3的基本概念和安装配置',
    completed: false,
    order: 1,
    createTime: Date.now() - 86400000 * 8
  },
  {
    id: 2,
    courseId: 1,
    title: '组件化开发',
    description: '掌握Vue 3的组件系统和Props传递',
    completed: false,
    order: 2,
    createTime: Date.now() - 86400000 * 7
  },
  {
    id: 3,
    courseId: 1,
    title: '响应式系统',
    description: '深入理解Vue 3的响应式原理',
    completed: false,
    order: 3,
    createTime: Date.now() - 86400000 * 6
  },
  // React 入门到精通课程的任务项
  {
    id: 4,
    courseId: 2,
    title: 'React 基础概念',
    description: '了解React的核心思想和基本使用',
    completed: false,
    order: 1,
    createTime: Date.now() - 86400000 * 6
  },
  {
    id: 5,
    courseId: 2,
    title: '状态管理',
    description: '学习React的状态管理技巧',
    completed: false,
    order: 2,
    createTime: Date.now() - 86400000 * 5
  },
  // Node.js 后端开发课程的任务项
  {
    id: 6,
    courseId: 3,
    title: 'Node.js 环境搭建',
    description: '安装和配置Node.js开发环境',
    completed: false,
    order: 1,
    createTime: Date.now() - 86400000 * 4
  }
]

// 模拟课程评价数据
const mockComments = [
  // Vue 3 实战开发课程的评价
  {
    id: 1,
    articleid: 1, // 对应courseId
    body: '这门课程非常棒，讲解清晰，实用性强！',
    userid: 1,
    username: '学习者小明',
    createTime: Date.now() - 86400000 * 4
  },
  {
    id: 2,
    articleid: 1,
    body: '老师讲得很好，案例丰富，很适合入门学习。',
    userid: 2,
    username: '前端新手',
    createTime: Date.now() - 86400000 * 3
  },
  // React 入门到精通课程的评价
  {
    id: 3,
    articleid: 2,
    body: '内容全面，从基础到进阶都有覆盖，推荐给想学习React的同学。',
    userid: 3,
    username: '开发者小李',
    createTime: Date.now() - 86400000 * 2
  },
  // Node.js 后端开发课程的评价
  {
    id: 4,
    articleid: 3,
    body: '课程内容充实，实战性强，学到了很多实用技能。',
    userid: 4,
    username: '全栈学习者',
    createTime: Date.now() - 86400000 * 1
  }
]

// 模拟课程类别数据
const mockCategories = [
  { id: 1, title: '前端开发', categoryType: '课程', courseCount: 3 },
  { id: 2, title: '后端开发', categoryType: '课程', courseCount: 2 },
  { id: 3, title: '移动开发', categoryType: '课程', courseCount: 1 },
  { id: 4, title: '数据科学', categoryType: '课程', courseCount: 0 }
]

// 模拟课程数据
const mockCourses = [
  {
    id: 1,
    title: 'Vue 3 实战开发',
    categoryid: 1,
    teacher: '张老师',
    courseTime: Date.now() - 86400000 * 5, // 5天前
    description: '本课程全面介绍Vue 3的核心概念和实战技巧，包括组合式API、响应式系统、组件化开发等内容。',
    userId: 1,
    createTime: Date.now() - 86400000 * 10,
    coverImage: '/placeholder/vue3-course.jpg'
  },
  {
    id: 2,
    title: 'React 入门到精通',
    categoryid: 1,
    teacher: '李老师',
    courseTime: Date.now() - 86400000 * 3, // 3天前
    description: '从零开始学习React框架，掌握组件开发、状态管理、React Router等实用技能。',
    userId: 1,
    createTime: Date.now() - 86400000 * 7,
    coverImage: '/placeholder/react-course.jpg'
  },
  {
    id: 3,
    title: 'Node.js 后端开发',
    categoryid: 2,
    teacher: '王老师',
    courseTime: Date.now() + 86400000 * 2, // 2天后
    description: '学习Node.js后端开发，掌握Express框架、MongoDB数据库操作和RESTful API设计。',
    userId: 2,
    createTime: Date.now() - 86400000 * 5,
    coverImage: '/placeholder/node-course.jpg'
  }
]

// Mock配置
const mockConfig = {
  // 控制是否使用mock数据
  useMock: true,
  // 模拟网络延迟(毫秒)
  delay: 300,
  // 模拟API成功率
  successRate: 0.95,
  // 模拟特定API失败
  failApis: []
}

// 模拟异步请求
const mockRequest = (data, options = {}) => {
  const { delay = mockConfig.delay, shouldFail = false } = options
  
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const isSuccess = !shouldFail && Math.random() < mockConfig.successRate
      
      if (isSuccess) {
        resolve({
          errno: 0,
          message: 'success',
          data
        })
      } else {
        reject(new Error('模拟API请求失败'))
      }
    }, delay)
  })
}

// Mock API方法
export const mockAPI = {
  // 获取所有课程类别
  getAllCategories: (type = '课程') => {
    const filtered = mockCategories.filter(cat => cat.categoryType === type)
    return mockRequest(filtered)
  },
  
  // 添加课程类别
  addCategory: (categoryData) => {
    const newId = Math.max(...mockCategories.map(cat => cat.id), 0) + 1
    const newCategory = {
      id: newId,
      title: categoryData.title,
      categoryType: categoryData.categoryType || '课程',
      courseCount: 0
    }
    mockCategories.push(newCategory)
    return mockRequest(newCategory)
  },
  
  // 获取所有课程
  getAllCourses: () => {
    return mockRequest(mockCourses)
  },
  
  // 添加课程
  addCourse: (courseData) => {
    const newId = Math.max(...mockCourses.map(course => course.id), 0) + 1
    const newCourse = {
      id: newId,
      title: courseData.title,
      categoryid: courseData.categoryid,
      teacher: courseData.teacher,
      courseTime: courseData.courseTime || Date.now(),
      description: courseData.description,
      userId: courseData.userId,
      createTime: Date.now(),
      coverImage: courseData.coverImage || '/placeholder/new-course.jpg'
    }
    mockCourses.push(newCourse)
    
    // 更新对应类别的课程数量
    const category = mockCategories.find(cat => cat.id === courseData.categoryid)
    if (category) {
      category.courseCount++
    }
    
    // 返回与getCourseByIdMock格式一致的数据，确保添加后能正确显示
    const courseResponse = {
      id: newCourse.id,
      title: newCourse.title,
      body: newCourse.description || '暂无课程介绍',
      categoryid: newCourse.categoryid,
      categoryName: mockCategories.find(c => c.id === newCourse.categoryid)?.title || '未知类别',
      teachername: newCourse.teacher || '未知老师',
      startTime: newCourse.courseTime || Date.now(),
      authorName: courseData.username || '23002944', // 使用提供的用户名或默认值
      addedTime: new Date(newCourse.createTime || Date.now()).toISOString()
    }
    
    return mockRequest(courseResponse)
  },
  
  // 获取单个课程
  getCourseById: (id) => {
    const course = mockCourses.find(c => c.id === id)
    return mockRequest(course || null)
  },
  
  // 切换Mock模式
  toggleMock: (useMock) => {
    mockConfig.useMock = useMock
  },
  
  // 获取Mock配置
  getConfig: () => ({
    ...mockConfig
  }),
  
  // 更新课程
  updateCourse: (courseId, courseData) => {
    const index = mockCourses.findIndex(c => c.id === parseInt(courseId))
    if (index !== -1) {
      mockCourses[index] = {
        ...mockCourses[index],
        ...courseData
      }
      return mockRequest(mockCourses[index])
    }
    return mockRequest(null, { shouldFail: true })
  },
  
  // 删除课程
  deleteCourse: (courseId) => {
    const index = mockCourses.findIndex(c => c.id === parseInt(courseId))
    if (index !== -1) {
      // 找到课程对应的类别并更新数量
      const course = mockCourses[index]
      const category = mockCategories.find(cat => cat.id === course.categoryid)
      if (category && category.courseCount > 0) {
        category.courseCount--
      }
      
      mockCourses.splice(index, 1)
      return mockRequest({ success: true })
    }
    return mockRequest(null, { shouldFail: true })
  }
}

export default mockAPI

// 获取课程任务项
const getCourseSubitems = (courseId) => {
  return mockSubitems.filter(item => item.courseId === courseId)
}

// 添加课程任务项
const addCourseSubitem = (courseId, subitemData) => {
  const newId = Math.max(...mockSubitems.map(item => item.id), 0) + 1
  const newSubitem = {
    id: newId,
    courseId,
    title: subitemData.title,
    description: subitemData.description || '',
    completed: false,
    order: mockSubitems.filter(item => item.courseId === courseId).length + 1,
    createTime: Date.now()
  }
  mockSubitems.push(newSubitem)
  return newSubitem
}

// 获取课程评价
const getCourseComments = (courseId) => {
  return mockComments.filter(comment => comment.articleid === courseId)
}

// 添加课程评价
const addCourseComment = (commentData) => {
  const newId = Math.max(...mockComments.map(comment => comment.id), 0) + 1
  const newComment = {
    id: newId,
    articleid: commentData.articleid,
    body: commentData.body,
    userid: commentData.userid || 1,
    username: commentData.username || '匿名用户',
    createTime: Date.now()
  }
  mockComments.push(newComment)
  return newComment
}

// 导出单独的mock函数供API使用
export const getCategoriesMock = () => mockCategories
export const getCoursesMock = () => mockCourses
export const addCourseMock = (courseData) => mockAPI.addCourse(courseData)
export const updateCourseMock = (courseId, courseData) => mockAPI.updateCourse(courseId, courseData)
export const deleteCourseMock = (courseId) => mockAPI.deleteCourse(courseId)

export const getCourseByIdMock = (courseId) => {
  const course = mockCourses.find(c => c.id === courseId)
  if (course) {
    // 转换为前端期望的完整课程详情结构
    return {
      id: course.id,
      title: course.title,
      body: course.description || '暂无课程介绍',
      categoryid: course.categoryid,
      categoryName: mockCategories.find(c => c.id === course.categoryid)?.title || '未知类别',
      teachername: course.teacher || '未知老师',
      startTime: course.courseTime || Date.now(),
      authorName: 'admin', // 默认作者名
      addedTime: new Date(course.createTime || Date.now()).toISOString()
    }
  }
  return null
}

export const getCourseSubitemsMock = (courseId) => {
  const subitems = getCourseSubitems(courseId)
  // 转换mock数据格式，确保返回的字段与CourseDetailView.vue所需一致
  return subitems.map(item => ({
    id: item.id,
    title: item.title,
    body: item.description || '', // description -> body
    addedTime: new Date(item.createTime).toISOString(), // createTime -> addedTime
    authorName: '23002944' // 添加默认作者名
  }))
}

export const addCourseSubitemMock = (courseId, subitemData) => {
  return addCourseSubitem(courseId, subitemData)
}

export const getCourseCommentsMock = (courseId) => {
  const comments = getCourseComments(courseId)
  // 转换mock数据格式，确保返回的字段与CourseDetailView.vue所需一致
  return comments.map(comment => ({
    id: comment.id,
    body: comment.body,
    userid: comment.userid,
    username: comment.username,
    addedTime: new Date(comment.createTime).toISOString() // createTime -> addedTime
  }))
}

export const addCourseCommentMock = (commentData) => {
  const newComment = addCourseComment(commentData)
  // 转换新添加的评论格式，确保包含addedTime字段
  return {
    id: newComment.id,
    body: newComment.body,
    userid: newComment.userid,
    username: newComment.username,
    addedTime: new Date(newComment.createTime).toISOString() // createTime -> addedTime
  }
}

// 导出mock配置
export { mockConfig }